import { createApp } from 'vue'
import Antd from 'ant-design-vue';
import App from './App.vue'


import 'ant-design-vue/dist/reset.css';

import '@/assets/style/style.scss'

import i18n from './i18n'

import { createPinia } from 'pinia';
import router from './router';
import components from './components';
import axios, { AxiosHeaders } from 'axios';
import { useAuthStore, useLangStore } from './store';
import { useI18nStore } from './store/i18n';
import { useResourceStore } from './store/resource';

axios.interceptors.request.use(function (config) {
    console.log(import.meta.env.B_DEFAULT_LOCALE)
    config.baseURL = import.meta.env.B_APIURL

    if(!config.headers) {
        config.headers = new AxiosHeaders()
    }

    config.headers.source = import.meta.env.B_DEVICE

    const locale = localStorage.getItem(import.meta.env.B_LOCALE_KEY)
    config.headers.locale = locale ? locale : import.meta.env.B_DEFAULT_LOCALE

    const authStore = useAuthStore()

    if(authStore.auth) {
        config.headers.Authorization = localStorage.getItem(import.meta.env.B_TOKEN_KEY) as string
    }

    return config;
})


axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    return response;
  }, function (error) {
    const authStore = useAuthStore()
    // if(error.response.status == 403) {
    //     authStore.logout()
    //     window.location.reload()
    //     return
    // }
    

    // 对响应错误做点什么
    return Promise.reject(error);
});




async function init() {
    
    const app = createApp(App)

    app.use(createPinia())

    const i18nStore = useI18nStore()
    await i18nStore.init()

    app.config.globalProperties.$t = i18nStore.t
    app.config.globalProperties.$j = i18nStore.join
    app.config.globalProperties.$c = i18nStore.concat

    //全局注册组件
    for(let key in components) {
        app.component(import.meta.env.B_COMPONENT_PREFIX + key, components[key])
    }

    app.use(i18n, import.meta.env.B_DEFAULT_LOCALE)

    app.use(Antd)

    app.use(router)

    const langStore = useLangStore()
    
    const resourceStore = useResourceStore()

    
    app.config.globalProperties.$translate = langStore.translate
    app.config.globalProperties.$hasPermission = resourceStore.hasPermission
    app.mount('#app')
}


init()




